package tpenchere.controllers;

import java.util.EventObject;

import javax.swing.ActionMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.jdesktop.application.Action;
import org.jdesktop.application.Application.ExitListener;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.Task;

import tpenchere.application.MainApplication;
import tpenchere.model.User;
import tpenchere.service.EnchereServiceOperations;
import tpenchere.service.MainContext;
import tpenchere.ui.AbstractView;
import tpenchere.ui.contents.LoginWindow;

/**
 * 
 */
public class LoginController extends DefaultController {

	/** the view is useful to retrieve info (e.g. the selected item) */
	private final LoginWindow view;

	public LoginController(LoginWindow pView) {
		view = pView;
	}
	
	@Action(name = "view.login.button.connection")
	public void connection() {
		String login = view.getLogin().getText();
		String password = view.getPassword().getText();
		EnchereServiceOperations serviceImpl = provider.getService();
		try {
			System.out.println("Trying connection with "+login+" and "+password);
			User u = serviceImpl.connect(login, password);
			
			if (u != null) {
				System.out.println("Connecting...");
				session.setLoggedUser(u);
				System.out.println("Switch to View...");
				this.switchToView(AbstractView.ViewType.HOME);
			} else {
				view.showError(resourceMap.getString("view.login.dialog.authentication.failed"),
								resourceMap.getString("view.login.dialog.authentication.failed.title"));
			}
		} catch (Exception e) {
			view.showError(resourceMap.getString("view.login.dialog.authentication.failed"),
					resourceMap.getString("view.login.dialog.authentication.failed.title"));
			e.printStackTrace();
		}
	}
	
	@Action(name = "view.login.button.register")
	public void register() {
		this.switchToView(AbstractView.ViewType.REGISTER);
	}
}
